package com.hzlj.position.job.job;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.hzlj.position.config.common.dto.jzJbxxDeviceBind.JzJbxxDeviceBindQueryResultDTO;
import com.hzlj.position.locate.common.dto.position.PositionAddResultDTO;
import com.hzlj.position.locate.service.DifferentiationDataService;
import com.hzlj.position.locate.service.PositionNewestService;

import java.util.Date;

/**
 * 获取位置的定时作业
 **/
public interface LocateTimerTaskJob {

    /**
     * 实时获取定位
     */
    PositionAddResultDTO fetchPosition(String jgCode,
                                       String jzId,
                                       String deviceCode,
                                       String channel);

    /**
     * 取消任务
     */
    void cancelTask(String jgCode,
                    String jzId,
                    String deviceCode,
                    String channel);

    /**
     * 添加任务
     */
    void addTask(String jgCode,
                 String jzId,
                 String deviceCode,
                 String channel,
                 Integer interval);

    default int getLocateDelay(PositionNewestService positionNewestService,
                               DifferentiationDataService differentiationDataService,
                               JzJbxxDeviceBindQueryResultDTO device) {
        Integer delay = differentiationDataService.getLocateJobDelay(device.getDeviceCode(), device.getChannel());
        if (delay != null) {
            return delay;
        }
        delay = 0;
        Date lastLocateTime = positionNewestService.getPositionTime(device.getJzId(), device.getDeviceCode());
        int interval = device.getLocateInterval();
        //计算延迟时间：如果最近定位时间在interval内，则需要加上间隔时间
        if (lastLocateTime != null) {
            long betweenInterval = DateUtil.between(lastLocateTime, new Date(), DateUnit.SECOND, false);
            delay = (int) (interval - Math.min(interval, betweenInterval));
        }
        return delay;
    }
}
